﻿/**
* 基础工具
*/
String.prototype.ItemIsContain = function (item) {
    var _input = this;
    var source = "," + _input + ",";
    item = "," + item + ",";
    return source.indexOf(item) > -1;
}
//Number.prototype.ItemIsContain = function (item) {
//    var _input = this;
//    var source = "," + _input + ",";
//    var str = "," + item.ToString() + ",";
//    return source.indexOf(str) > -1;
//}
String.prototype.ItemAdd = function (item) {
    var _input = this;
    var source = "," + _input + ",";
    if (source.indexOf("," + item + ",") > -1) {
    }
    else {
        source = source + item;
    }
    return source.trim(',').trim(',');
};
String.prototype.ItemRemove = function (item) {
    var _input = this;
    if (!item) return _input;
    var itemArray = item.Split(',');
    var source = "," + _input + ",";
    source = source.Replace("," + item + ",", "");
    return source.trim(',');
};

/**
去掉字符后面的空格和去掉'
*/
//String.prototype.trim = function () { return this.replace(/(^\s+)|(\s+$)/g, ""); }

String.prototype.trim = function (dot) {
    var result = this;
    if (!dot)
        result = result.replace(/(^\s+)|(\s+$)/g, "");
    else {
        if (result.indexOf(dot) == 0)
            result = result.substring(1, result.length);
        if (result.lastIndexOf(dot) == result.length - 1) {
            result = result.substring(0, result.length - 1);
        }
    }
    return result;
};

//去掉前后的逗号
String.prototype.trimdot = function () {
    var _result = this;
    if (_result.indexOf(",") == 0)
        _result = _result.substring(1, _result.length + 1);
    if (_result.lastIndexOf(",") == _result.length - 1)
        _result = _result.substring(0, _result.length - 1);
    return _result;
};
//去掉单引号
String.prototype.trimquote = function () { return this.replace("'", ""); };
String.prototype.substringPro = function (length, suffix) {
    var str = '';
    suffix = suffix || '';
    if (this.getLen() <= length) {
        return this;
    }
    for (var i = 0, j = 0; j < length - suffix.length;) {
        if (this.charCodeAt(i) >= 0 && this.charCodeAt(i) < 256) {
            str += this.charAt(i);
            j++;
        } else if ((j += 3) <= length) {
            str += this.charAt(i);
        }
        i++;
    }
    str += suffix;
    return str;
};
String.prototype.getRootDomain = function () {
    var res = /^([^:]*:\/\/)?([^\/\.]+\.([^\/]+))/.exec(this);
    return res && res[3] !== undefined ? res[3] + '' : '';
};
String.prototype.replaceAll = function (s1, s2) {
    return this.replace(new RegExp(s1, "gm"), s2);
};
String.prototype.getLen = function (p_bolMulti) {
    if ('undefined' == typeof p_bolMulti) {
        p_bolMulti = true;
    } else {
        p_bolMulti = false;
    }
    var len = 0;
    if (p_bolMulti) {
        for (var i = 0; i < this.length; ++i) {
            if (this.charCodeAt(i) > 127) {
                len += 3;
            } else {
                len++;
            }
        }
    } else {
        len = this.length;
    }
    return len;
};
String.prototype.chkLen = function (minLen, maxLen) {
    var strlen = this.getLen(this);
    if (strlen > maxLen || strlen < minLen) {
        return false;
    } else {
        return true;
    }
};


/**格式验证 number int url email idcard area money year input username_cn cn phone mobile date */
String.prototype.chkType = function (type) {
    switch (type) {
        case 'number':
            return (/^[\+\-]?\d*?\.?\d*?$/).test(this);
        case 'int':
            return (/^-?[1-9][0-9]+$|^-?[0-9]$/).test(this);
        case 'url':
            return (/^https?:\/\/([a-z0-9-]+\.)+[a-z0-9]{2,4}.*$/).test(this);
        case 'email':
            return (/^[a-z0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,4}$/i).test(this);
        case 'idcard':
            return (/^[0-9]{15}$|^[0-9]{17}[a-zA-Z0-9]/).test(this);
        case 'area':
            return (/^\d+(\.\d{1,2})?$/).test(this);
        case 'money':
            return (/^\d+(\.\d{1,2})?$/).test(this);
        case 'year':
            return (/^(19|20)\d\d$/).test(this);
        case 'input':
            return (/^[\u4e00-\u9fa5A-Za-z0-9_\s\~\@\!\#\$\.\,\/\\\%\^\&\*\(\)_\+\?\>\<《〉》\:：〉、，。？！￥（）\{\}\[\]]+$/).test(this);
        case 'username':
            return (/^[\u4e00-\u9fa5]/).test(this);
        case 'cn':
            return (/^[\u4e00-\u9fa5]/).test(this);
        case 'phone':
            return (/^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/).test(this);
        case 'mobile':
            return (/^\d{11,13}$/).test(this);
        case 'date':
            return (/^(\d{2,4})[\-\/](\d{1,2})[\-\/](\d{1,2})$/).test(this);
        case 'minDate':
            return (/^(\d{2,4})\-(\d{1,2})\-(\d{1,2})$/).test(this);
        case 'time':
            return (/^(\d{2,4})\-(\d{1,2})\-(\d{1,2}) ([0-1][0-9]|2[0-3]|^[0-9]):([0-5]?[0-9]):([0-5]?[0-9])$/).test(this);
        //case 'phoneOrMobile':
        //    return (/^1[3|4|5|8|7][0-9]\d{8}$/.test(this) ||
        //    /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/i.test(this)
            //      );;
        case 'phoneOrMobile':
            return (/[\d-]+/).test(this);
        case 'safepass':
            return !(/^(([A-Z]*|[a-z]*|\d*|[-_\~!@#\$%\^&\*\.\(\)\[\]\{\}<>\?\\\/\'\"]*)|.{0,5})$|\s/.test(this));
        case 'CHS':
            return /^[\u4e00-\u9fa5]+$/.test(this);
        case 'IDNUMBER':
            return /^(\d{18,18}|\d{15,15}|\d{17,17}[xX]?)$/.test(this);
            break;
    }
    return false;
};
/**计算字符出现次数*/
String.prototype.getCount = function (str) {
    var ___r___ = new RegExp(str, 'gi');
    var g = this;
    return g.match(___r___).length;
    //return this;
};

/**全角字符转半角字符
**/
String.prototype.dbcToSbc = function () {
    var result = "";
    for (var i = 0; i < this.length; i++) {
        if (this.charCodeAt(i) == 12288) {
            result += String.fromCharCode(this.charCodeAt(i) - 12256);
            continue;
        }
        if (this.charCodeAt(i) > 65280 && this.charCodeAt(i) < 65375)
            result += String.fromCharCode(this.charCodeAt(i) - 65248);
        else
            result += String.fromCharCode(this.charCodeAt(i));
    }
    return result;
};
/**null等转成空字符串
*/
String.prototype.cleanNull = function () {
    if (this == undefined || this == null || this == "")
        return "";
    else
        return this;
}
//获取年的前两位
function getPrefixYear() {
    var y = (new Date()).getFullYear();
    return parseInt(y / 100);
}
//如果日期是14-2-2类型的，自动加上前缀，参数是日期字符串
function fixDatePrefix(date) {
    date = date.replace("-", "/");
    var _p = date.indexOf("/");
    var _year = date.substring(0, _p);
    if (_year.length == 2)
        date = getPrefixYear() + date;
    return date;
}
/**
字符串转成日期格式
*/
String.prototype.toDate = function () {
    if (!this) return "";
    var temp = this;
    if (temp.indexOf("Date(") > -1) {
        var date_c;
        eval("date_c=new " + temp.replaceAll("/", "") + ";");
        return date_c;
    }
    else {
        if (temp.indexOf('+') > -1)
            temp = this.replace("+", " ");
        if (temp.indexOf('T') > -1)
            temp = temp.replace('T', ' ');
        if (temp.indexOf('.') > -1)
            temp = temp.substring(0, this.indexOf('.'));
        if (temp.length > 19)
            temp = temp.substring(0, 19);
        temp = fixDatePrefix(temp);
        toDate = new Date(Date.parse(temp.replace(/-/g, "/")));
    }
    return toDate;
}
String.prototype.toDateTime = function () {
    var temp = this;
    if (temp.indexOf('+') > -1)
        temp = this.substring(0, this.indexOf('+'));
    if (temp.indexOf('T') > -1)
        temp = temp.replace('T', ' ');
    if (temp.indexOf('.') > -1)
        temp = this.substring(0, this.indexOf('.'));
    toDate = new Date(Date.parse(temp.replace(/-/g, "/")));
    return toDate;
}
String.prototype.format = function (args) {
    if (arguments.length > 0) {
        var result = this;
        if (arguments.length == 1 && typeof (args) == "object") {
            for (var key in args) {
                var reg = new RegExp("({" + key + "})", "g");
                result = result.replace(reg, args[key]);
            }
        }
        else {
            for (var i = 0; i < arguments.length; i++) {
                if (arguments[i] == undefined) {
                    return "";
                }
                else {
                    var reg = new RegExp("({[" + i + "]})", "g");
                    result = result.replace(reg, arguments[i]);
                }
            }
        }
        return result;
    }
    else {
        return this;
    }
}
/*
字符串转Json格式数据
*/
$.par2Json = function (string, overwrite) {
    //&实体运算符先替换掉
    if (!string) return {};
    string = decodeHTML(string);
    var obj = {}, pairs = string.split('&'), d = decodeURIComponent, name, value;
    $.each(pairs, function (i, pair) {
        var temp = pair.replaceAll('\n', '');
        var pos = temp.indexOf('=');

        if (pos > -1) {
            name = d(temp.substring(0, pos));
            value = (temp.substring(pos + 1, temp.length));
            try{
                value=d(value);}
            catch (e) {

            }
            obj[name] = overwrite || !obj[name] ? value : [].concat(obj[name]).concat(value);
        }
    });
    return obj;
};
/**
格式化日期
*/
Date.prototype.format = function (format) {
    var o =
    {
        "M+": this.getMonth() + 1, //month
        "d+": this.getDate(),    //day
        "h+": this.getHours(),   //hour
        "m+": this.getMinutes(), //minute
        "s+": this.getSeconds(), //second
        "q+": Math.floor((this.getMonth() + 3) / 3),  //quarter
        "S": this.getMilliseconds() //millisecond
    }
    if (/(y+)/.test(format))
        format = format.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(format))
            format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
    return format;
}

/**计算时间差,返回天数
*/
Date.daysBetween = function (DateOne, DateTwo) {
    var OneMonth = DateOne.substring(5, DateOne.lastIndexOf('-'));
    var OneDay = DateOne.substring(DateOne.length, DateOne.lastIndexOf('-') + 1);
    var OneYear = DateOne.substring(0, DateOne.indexOf('-'));

    var TwoMonth = DateTwo.substring(5, DateTwo.lastIndexOf('-'));
    var TwoDay = DateTwo.substring(DateTwo.length, DateTwo.lastIndexOf('-') + 1);
    var TwoYear = DateTwo.substring(0, DateTwo.indexOf('-'));
    var cha = ((Date.parse(OneMonth + '/' + OneDay + '/' + OneYear) - Date.parse(TwoMonth + '/' + TwoDay + '/' + TwoYear)) / 86400000);
    return cha;
}
//重写toFixed方法
Number.prototype.toFixed = function (len) {
    var tempNum = 0;
    var s, temp;
    var s1 = this + "";
    var start = s1.indexOf(".");

    //截取小数点后,0之后的数字，判断是否大于5，如果大于5这入为1

    if (s1.substr(start + len + 1, 1) >= 5)
        tempNum = 1;

    //计算10的len次方,把原数字扩大它要保留的小数位数的倍数
    var temp = Math.pow(10, len);
    //求最接近this * temp的最小数字
    //floor() 方法执行的是向下取整计算，它返回的是小于或等于函数参数，并且与之最接近的整数
    s = Math.floor(this * temp) + tempNum;
    return s / temp;

}


///处理safari的日期问题
function parseDate(input, format) {
    format = format || 'yyyy-MM-dd hh:mm:ss'; // default format
    var parts = input.match(/(\d+)/g),
      i = 0, fmt = {};
    // extract date-part indexes from the format
    format.replace(/(yyyy|dd|MM|hh|mm|ss)/g, function (part) { fmt[part] = i++; });

    return new Date(parts[fmt['yyyy']], parts[fmt['MM']] - 1, parts[fmt['dd']], parts[fmt['hh']], parts[fmt['mm']], parts[fmt['ss']]);
}
function randomInt(x1, x2) {
    var min_int = parseInt(x1);
    var max_int = parseInt(x2);
    if (isNaN(min_int) || isNaN(max_int)) {
        alert('parameter error');
        return false;
    }

    x1 = Math.min(min_int, max_int);
    x2 = Math.max(min_int, max_int);

    return x1 + Math.floor(Math.random() * (x2 - x1 + 1));
}
function winId() { return "win-" + (new Date()).format("yyyyMMddhhmmssS"); }

function getDayOfWeek(day) {
    // var day = new Date(Date.parse(dayValue.replace(/-/g, '/')));   //将日期值格式化 
    var today = new Array("周日", "周一", "周二", "周三", "周四", "周五", "周六");  //创建星期数组
    return today[day.getDay()];   //返一个星期中的某一天，其中0为星期日 
}
function encodeHTML(str) {
    var s = "";
    if (str.length == 0) return "";
    s = str.replace(/&/g, "&gt;");
    s = s.replace(/</g, "&lt;");
    s = s.replace(/>/g, "&gt;");
    s = s.replace(/ /g, "&nbsp;");
    s = s.replace(/\'/g, "'");
    s = s.replace(/\"/g, "&quot;");
    s = s.replace(/\n/g, "<br>");
    return s;
}
function html2txt(str, noEnter) {
    return str.replace(/<\/?.+?>/g, ""); //去掉所有的html标记
}
function decodeHTML(str) {
    var s = "";
    if (str.length == 0) return "";
    s = str.replace(/&amp;/g, "&");
    s = s.replace(/&lt;/g, "<");
    s = s.replace(/&gt;/g, ">");
    s = s.replace(/&nbsp;/g, " ");
    s = s.replace(/'/g, "\'");
    s = s.replace(/&quot;/g, "\"");
    s = s.replace(/<br>/g, "\n");
    return s;
}
function GetNullToString(o) {
    if (o == undefined || o == null || o == "" || o == "undefined")
        return "";
    else
        return o;
}
function GetNullToInt(o) {
    if (o == undefined || o == null || o == "")
        return 0;
    else
        return o;
}
/**
下拉框操作
*/
jQuery.fn.size = function () {
    var ______i = 0;
    $(this).find("option").each(function () {
        ______i++;
    });
    return ______i;
}
//获得选中项的索引   
jQuery.fn.getSelectedIndex = function () {
    return jQuery(this).get(0).selectedIndex;
}
//获得当前选中项的文本
jQuery.fn.getSelectedText = function () {
    if (this.size() == 0) { } // return "下拉框中无选项";
    else {
        var index = this.getSelectedIndex();
        if (index < 0) return;
        return jQuery(this).get(0).options[index].text;
    }
}
//获得当前选中项的值
jQuery.fn.getSelectedValue = function () {
    if (this.size() == 0)
        // return "下拉框中无选中值";
    { }
    else
        return jQuery(this).val();
}
//设置select中值为value的项为选中   
jQuery.fn.setSelectedValue = function (value) {
    jQuery(this).get(0).value = value;
}
//设置select中文本为text的第一项被选中   
jQuery.fn.setSelectedText = function (text) {
    var isExist = false;
    var count = this.size();
    for (var i = 0; i < count; i++) {
        if (jQuery(this).get(0).options[i].text == text) {
            jQuery(this).get(0).options[i].selected = true;
            isExist = true;
            break;
        }
    }
    if (!isExist) {
        //        alert("下拉框中不存在该项");
    }
}
//设置选中指定索引项   
jQuery.fn.setSelectedIndex = function (index) {
    var count = this.size();
    if (index >= count || index < 0) {
        //        alert("选中项索引超出范围");
    }
    else {
        jQuery(this).get(0).selectedIndex = index;
    }
}
//判断select项中是否存在值为value的项   
jQuery.fn.isExistItem = function (value) {
    var isExist = false;
    var count = this.size();
    for (var i = 0; i < count; i++) {
        if (jQuery(this).get(0).options[i].value === value) {
            isExist = true;
            break;
        }
    }
    return isExist;
}
//向select中添加一项，显示内容为text，值为value,如果该项值已存在，则提示   
jQuery.fn.addOption = function (text, value) {
    if (this.isExistItem(value)) {
        //        alert("待添加项的值已存在");
    }
    else {
        jQuery(this).get(0).options.add(new Option(text, value));
    }
}
jQuery.fn.addOptionIndex = function (text, value, index) {
    $("<option value=" + value + ">" + text + "</option>").insertAfter(jQuery(this).find("option[value='" + index + "']"));
}
jQuery.fn.addOptionPosition = function (text, value, Position) {
    $("<option value=" + value + ">" + text + "</option>").insertBefore(jQuery(this).get(0).options[Position]);
}
/**
给下拉列表从webservice里获取值
*/
jQuery.fn.loadData = function (Url, Param, KeyField, DataField, DefaultText, DefaultValue) {
    var _select = this;
    var _selectval = _select.val();
    //_selectval = _select.val();
    jQuery.get(Url, Param, function (v) {
        _select.empty();

        _select.get(0).options.add(new Option(DefaultText, DefaultValue));
        jQuery(v).find("ds").each(function (v1, k1) {
            _select.get(0).options.add(new Option($(k1).find(DataField).text(), $(k1).find(KeyField).text()));
        });
        _select.val(_selectval);
    });
}
//删除select中值为value的项，如果该项不存在，则提示   
jQuery.fn.removeItem = function (value) {
    if (this.isExistItem(value)) {
        var count = this.size();
        for (var i = 0; i < count; i++) {
            if (jQuery(this).get(0).options[i].value == value) {
                jQuery(this).get(0).remove(i);
                break;
            }
        }
    }
    else {
        //        alert("待删除的项不存在!");
    }
}
//删除select中指定索引的项   
jQuery.fn.removeIndex = function (index) {
    var count = this.size();
    if (index >= count || index < 0) {
        //        alert("待删除项索引超出范围");
    }
    else {
        jQuery(this).get(0).remove(index);
    }
}
//删除select中选定的项   
jQuery.fn.removeSelected = function () {
    var index = this.getSelectedIndex();
    this.removeIndex(index);
}
//清除select中的所有项   
jQuery.fn.clearAll = function () {
    jQuery(this).get(0).options.length = 0;
}

/**
数组操作*/
Array.prototype.max = function () {
    return Math.max.apply({}, this)

}
Array.prototype.min = function () {
    return Math.min.apply({}, this)

}
Array.prototype.unique = function () {
    var hash = {};
    for (var i = 0, j = 0; i < this.length; i++) {
        if (this[i] !== undefined) {
            if (!hash[this[i]]) {
                this[j++] = this[i];
                hash[this[i]] = true;
            }
        }
    }
    this.length = j;
    return this;
};
Array.prototype.clone = function () {
    var arr = [];
    for (var p in this) {
        if (arr[p] === undefined && typeof this[p] == 'string') {
            arr[p] = this[p];
        }
    }
    return arr;
};
Array.prototype.insertAt = function (index, value) {
    var part1 = this.slice(0, index);
    var part2 = this.slice(index);
    part1.push(value);
    return (part1.concat(part2));
};
///是否包含
Array.prototype.indexOf = function (value) {
    for (var __jj__ = 0; __jj__ < this.length; __jj__++) {
        if (this[__jj__] == value) {
            return __jj__;
            break;
        }
    }
    return -1;
};
Array.prototype.del = function (n) {
    //n表示第几项，从0开始算起。
    //prototype为对象原型，注意这里为对象增加自定义方法的方法。
    //    if (n < 0)  //如果n<0，则不进行任何操作。
    //    {
    //        return this;
    //    }
    //    else {
    //        delete (this[n]);
    //        return this;
    //        return this.slice(0, n).concat(this.slice(n + 1, this.length));
    //    }

    //prototype为对象原型，注意这里为对象增加自定义方法的方法。
    if (n < 0)//如果n<0，则不进行任何操作。
        return this;
    else
        return this.slice(0, n).concat(this.slice(n + 1, this.length));
    /*
　　　concat方法：返回一个新数组，这个新数组是由两个或更多数组组合而成的。
　　　　　　　　　这里就是返回this.slice(0,n)/this.slice(n+1,this.length)
　　 　　　　　　组成的新数组，这中间，刚好少了第n项。
　　　slice方法： 返回一个数组的一段，两个参数，分别指定开始和结束的位置。
　　*/
}
//*/
function QueryString() {
    var name, value, i;
    var str = location.href;
    var num = str.indexOf("?");
    str = str.substr(num + 1);
    str = str.replace("#", "&");
    var arrtmp = str.split("&");
    for (i = 0; i < arrtmp.length; i++) {
        num = arrtmp[i].indexOf("=");
        if (num > 0) {
            name = arrtmp[i].substring(0, num); value = arrtmp[i].substr(num + 1);
            this[name] = value
        }
    }
}

var SiteTracker = function () {
    var _q = new QueryString();
    this.q = _q;    //地址栏参数
    var _tempP = GetNullToInt(_q.p);
    this.page = _tempP == 0 ? 1 : _tempP; //当前页
    this.pagesize = 20; //每页大小
    this.pagetotal = 1;
    //    this.title = "";    //标题参数
    var strUrl = window.location.href;
    var arrUrl = strUrl.split("/");
    var strPage = arrUrl[arrUrl.length - 1];
    this.module = arrUrl[arrUrl.length - 2];
    arrUrl = strPage.split(".");
    this.action = arrUrl[0];
    this.path = "/" + this.module + "/" + this.action;
}
var siteTracker = new SiteTracker();

/**Cookie*/
function GetCookieVal(offset) { var endstr = document.cookie.indexOf(";", offset); if (endstr == -1) endstr = document.cookie.length; var returnvalue = unescape(document.cookie.substring(offset, endstr)); returnvalue = (returnvalue == null || returnvalue == '') ? null : returnvalue; return returnvalue; } function SetCookie(sName, sValue, oExpires, sPath, sDomain, bSecure) {
    var sCookie = sName + "=" + (sValue); if (oExpires) { sCookie += "; expires=" + oExpires.toGMTString(); } else
        sCookie += "; expires=Tuesday, 01-Dec-2050 12:00:00 GMT"; if (sPath) { sCookie += "; path=" + sPath; } if (sDomain) { sCookie += "; domain=" + sDomain; } if (bSecure) { sCookie += "; secure"; } document.cookie = sCookie;
} function DelCookie(name) {
    var exp = new Date(); exp.setTime(exp.getTime() - 1); var cval = GetCookie(name); if (cval != "" || cval != null) document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString(); else
        return;
}
function GetCookie(name) { var arg = name + "="; var alen = arg.length; var clen = document.cookie.length; var i = 0; while (i < clen) { var j = i + alen; if (document.cookie.substring(i, j) == arg) return GetCookieVal(j); i = document.cookie.indexOf(" ", i) + 1; if (i == 0) break; } return null; } function GetCookieKey(name, key) { var myCookie = GetCookie(name); if (myCookie == null) return null; var clen = myCookie.length; var myCookies = myCookie.split("&"); var item; for (var i = 0; i < myCookies.length; i++) { item = myCookies[i].split("="); if (item[0] == key) { return item[1]; break; } } return ""; }
function callPageRender() {
    for (var _i = 0; _i < arguments.length; _i++) {
        var _item = arguments[_i];
        if ('undefined' != typeof window[_item]) {
            if (window[_item].render)
                window[_item].render();
        }
    }
}

function replaceJsTemplate(_template) {
    //模板替换
    var _temp = _template;
    var reg = /\[\!\-\-\{([^}]*?)\}\-\-\]/g;
    var _temp1 = _temp.replace(reg, function ($1, $2) {
        var _result = "";
        eval("_result=" + $2.replace("&gt;", ">").replace("&lt;", "<"));
        return _result;
    });
    return _temp1;
}
/**加密 text可以是十六进制字符串，或数字数组 
charset值：Hex Utf8*/
function aes(key, iv, text, charset) {
    key = CryptoJS.enc.Utf8.parse(key);
    iv = CryptoJS.enc.Utf8.parse(iv);
    if (!charset) charset = 'Hex';
    if (typeof (text) != 'string') {
        var combin = "";
        for (var i = 0; i < text.length; i++) {
            var tempHex = padNumber(text[i].toString(16), 2);
            combin += tempHex;
        }
        text = combin;
    }
    text = CryptoJS.enc[charset].parse(text);
    var encrypted = CryptoJS.AES.encrypt(text, key, { iv: iv, mode: CryptoJS.mode.CBC });
    return encrypted.ciphertext.toString(); // encrypted.toString();
}
//aes解密
function deaes(key, iv, text, charset) {
    key = CryptoJS.enc.Utf8.parse(key);
    iv = CryptoJS.enc.Utf8.parse(iv);
    if (!charset) charset = 'Hex';

    if (typeof (text) != 'string') {
        var combin = "";
        for (var i = 0; i < text.length; i++) {
            var tempHex = padNumber(text[i].toString(16), 2);
            combin += tempHex;
        }
        text = combin;
    }

    text = CryptoJS.enc[charset].parse(text);

    var result = CryptoJS.AES.decrypt({ ciphertext: text }, key, { iv: iv, mode: CryptoJS.mode.CBC });
    var resultstr = result.toString(CryptoJS.enc.Hex); //第一次解密结果
    return resultstr;
}
(function ($) {
    $.fn.fillForm = function (options) {
        var defaults = { params: {}, url: '', data: {}, filter: null, after: null };
        var opts = $.extend(defaults, options);
        var $form = this;
        if ((!!opts.url) && (!!opts.data)) {
            $.ajax({
                type: "get",
                url: opts.url,
                dataType: "json",
                contentType: "application/json;utf-8",
                data: opts.data,
                success: function (data) {
                    opts.params = data.d;
                    if (opts.filter) {
                        opts.filter(opts.params);
                    }
                }, async: false
            });
        }
        if (opts.params) {
            window[$($form[0]).attr("name")] = opts.params;
            $form.find("*").each(function (i, item) {
                if ($(item).is("input") || $(item).is("select") || $(item).is("textarea")) {
                    var name = $(item).attr("name");
                    var val = opts.params[name];
                    if ((val!=null) && (val!=undefined) && ((typeof val)!='undefined') && (val!=NaN)) {
                        val = val + "";
                        if (!$(item).is("textarea")) {
                            if (/Date\(\-?\d*\)/.test(val)) {
                                val = val.toDate().format("yyyy-MM-dd");
                            }
                        }

                        if (/Date\(\d*\)/.test(val)) {
                            val = val.toDate().format("yyyy-MM-dd");
                        }
                        val = val.replace(/\+/g, "");

                        if ($(item).is("input")) {
                            switch ($(item).attr("type")) {
                                case "text":
                                    $(item).val(val);
                                    break;
                                case "hidden":
                                    $(item).val(val);
                                    //for extjs datebox 日期控件，fillForm后触发日期控件赋值
                                    if ($(item).hasClass('datebox-f')) {
                                        $(item).change();
                                    }
                                    break;
                                case "radio":
                                    $(item).each(function (k, v) {
                                        if ($(v).val() == val || '') {
                                            $(v).prop("checked", true);
                                        }
                                    });
                                    break;
                                case "checkbox":
                                    $(item).each(function (k, v) {
                                        var vals = val.split(',');
                                        for (var j = 0; j < vals.length; j++) {
                                            if ($(v).val() == vals[j]) {
                                                $(v).prop("checked", true);
                                                break;
                                            }
                                        }
                                    });
                                    break;
                                default:
                                    $(item).val(val);
                                    $(item).attr("value", val);
                                    break;
                            }
                        }
                        else if ($(item).is("select")) {
                            if (val.chkType("int")) {
                                $(item).val(parseInt(val));
                            } else
                                $(item).val(val);
                            $(item).attr("value", val);
                            $(item).find("option[value='" + val + "']").prop("selected", true);
                            if ($(item).hasClass("form-select")) {
                                $(item).attr("value", val);
                                $(item).selectpicker("refresh");
                            }
                        }
                        else if ($(item).is("textarea")) {
                            $(item).val(val);
                        }
                        else if ($(item).is("img")) {
                            $(item).attr("src", val);
                        }
                    }
                } else if ($(item).is("a")) {
                    if ($(item).attr("name")) {
                        var _href = $(item).attr("href") || '';
                        _href = replaceJsTemplateInner(_href);
                        $(item).attr("href", _href);

                        var _arg = $(item).attr("arg0") || '';
                        _arg = replaceJsTemplateInner(_arg);
                        $(item).attr("arg0", _arg);

                    }
                }
                else if ($(item).text().indexOf("[!--") > -1) {
                    var _html = $(item).html();
                    _html = replaceJsTemplate(_html);
                    $(item).html(_html);
                }
                else if ($(item).attr("data-val")) {
                    var _property = $(item).attr("data-val");
                    var _result = "";
                    eval("_result=" + _property);
                    $(item).html(_result);
                }

            });
        }
        if (opts.after) {
            opts.after(opts.params);
        }
        function replaceJsTemplateInner(_template) {
            //模板替换
            var _temp = _template;
            var reg = /\[\!\-\-\{([^}]*?)\}\-\-\]/g;
            var _temp1 = _temp.replace(reg, function ($1, $2) {
                var _result = "";
                eval("_result=" + $2.replace("&gt;", ">").replace("&lt;", "<"));
                return _result;
            });
            return _temp1;
        }
    }
})(jQuery);

function getNextElement(field) {
    var form = field.form;
    for (var e = 0; e < form.elements.length; e++) {
        if (field == form.elements[e])
            break;
    }
    return form.elements[++e % form.elements.length];
}

document.onkeydown = function (event) {
    var e = event.srcElement;
    var isie = (document.all) ? true : false;
    if (event.keyCode == 13 && ((e.tagName == "INPUT") || (e.tagName == "SELECT"))) {
        var $win = $(event.target).parents('.window-body');
        if (!$win) return true;
        if ($(event.target).hasClass("xclass-submit")) {
            $win.find(".dialog-button").find(".l-btn-text:contains('保存')").parent().parent()[0].click();
            return false;
        } else if (e.type == 'submit') {
            $(event.target).click();
            return false;
        }
        if (isie) {
            event.keyCode = 9;
        }
        else {
            var el = getNextElement(event.target);
            //if (el.type == 'submit') {
            //    $(el).click();
            //}
            //else
            if (el.type != 'hidden')
                el.focus();
            else {
                var i = 0;
                while (el.type == 'hidden') {
                    el = getNextElement(el);
                }
            }
            el.focus();
            return false;
        }
    }
}
$.fn.xBindData = function (options) {
    /// <summary>给select绑定service数据源，给标签的value1属性赋值，可以自动选择预设值,default默认值优先级高。rowobj有值时，不读取服务端</summary>
    /// <returns>无返回</returns>
    var opts = $.extend({}, $.fn.xBindData.defaults, options);
    $.fn.xBindData.load(this, opts);
}
$.fn.xBindData.defaults = { "rowobj": null, "url": "", "text": "", "value": "", "data": "", "async": true, "defaultval": "" };
$.fn.xBindData.load = function (_control, options) {
    if (options.rowobj) {
        $.fn.xBindData.fill(_control, options, options.rowobj);
    }
    else {
        $.ajax({
            type: "get",
            url: options.url,
            dataType: "json",
            contentType: "application/json;utf-8",
            data: options.data,
            async: options.async,
            success: function (data) {
                var rows = loadFilter(data).rows;
                $.fn.xBindData.fill(_control, options, rows);
            }
        });
    }
}
$.fn.xBindData.fill = function (_control, options, rows) {
    _control.find("option:gt(0)").remove();
    $.map(rows, function (item) {
        _control.addOption(item[options.text], item[options.value]);
    });
    if (_control.attr("value") || _control.attr("value1")) {
        if (_control.attr("value1"))
            _control.val(_control.attr("value1"));
        else if (_control.attr("value"))
            _control.val(_control.attr("value"));

    }
    if (options.defaultval) _control.val(options.defaultval);
}
function getRemoteObject(url, data) {
    /// <summary>从服务器同步获取一个对象</summary>
    /// <param name="url" type="String">Service地址</param>
    /// <param name="data" type="String">请求数据</param>
    /// <returns></returns>
    var _tempobj = {};
    $.ajax({
        type: "get",
        url: url,
        dataType: 'json',
        data: data,
        contentType: "application/json;utf-8",
        success: function (data) {
            _tempobj = data.d;
        }, async: false
    });
    return _tempobj;
}
function getRemoteRows(url, data,callback) {
    /// <summary>从服务器同步获取一个rows</summary>
    /// <param name="url" type="String">Service地址</param>
    /// <param name="data" type="String">请求数据</param>
    /// <returns></returns>
    var _rows = [];
    $.ajax({
        type: "get",
        url: url,
        dataType: 'json',
        data: data,
        contentType: "application/json;utf-8",
        success: function (data) {
            _rows = loadFilter(data).rows;
            if (callback) callback(_rows);
        }, async: false
    });
    return _rows;
}
function  loadFilter (data) {
    if (!data.d) {
        data.d = { Table: {} };
    }
    if (!data.d.Table) data.d.Table = {};
    if (data.d.Total)
        data.d.Table.total = data.d.Total;
    else
        data.d.Table.total = 0;
    if (!data.d.Table.rows) data.d.Table.rows = [];
    return data.d.Table;
}
function rowsToObj(rows, key) {
    /// <summary>数组转成以key为键值的数组</summary>
    /// <returns>返回对象</returns>
    var obj = {};
    $.map(rows, function (item) {
        obj[item[key]] = item;
    });
    return obj;
}